<?php
if(!defined('IN_BSTO')){ die('[ERROR] You cannot load this page directly !!!'); }

Class Template {
	/*
	 * @the registry
	 * @access private
	 */
	private $configuration  = array();

	private $registry       = null;

	/*
	 * @Variables array
	 * @access private
	 */
	private $vars           = array();
	private $moduleTags     = array();

	private $menuKey = '';
	private $menuKeyACP = '';

	/**
	 *
	 * @constructor
	 *
	 * @access public
	 *
	 * @return void
	 *
	 */
	function __construct($registry) {
		//print_r($registry);
		$this->registry = $registry;

		include('views/configuration.php');

		$this->configuration = $template;
	}


	/**
	 *
	 * @set undefined vars
	 *
	 * @param string $index
	 *
	 * @param mixed $value
	 *
	 * @return void
	 *
	 */
	public function __set($index, $value)
	{
		$this->vars[$index] = $value;
	}


	public function getTemplate($name, array $tags = array(), $type)
	{
		
		$tags['bstoPath']	  = dirname(BSTO_ROOT_PATH);
		$tags['bstoRootPath'] = BSTO_ROOT_PATH;
		$tags['bstoViewPath'] = BSTO_ROOT_PATH. 'views/';
        $tags['statisticURL'] = $user = $this->registry->db->get('configManager')->statisticURL;
        $tags['facebookAPI']  = $user = $this->registry->db->get('configManager')->appID;
        
		$tags = $this->getMenuTemplateReplace($tags);

		$path = BSTO_PATH . ($this->registry->admincp?'/admincp':'') . '/views' . '/' . $name . $type . '.php';

		if (file_exists($path) == false){
			throw new Exception('Template not found in '. $path);
			return false;
		}

		//echo $tags['bstoViewPath']."\n";
		$template = file_get_contents($path);
		foreach($tags as $tag => $value){
			$template = str_replace('{'.$tag.'}', $value, $template);
		}
		
		
		return $template;
	}

	public function getModule($name, array $tags = array()){
		return $this->getTemplate($name, $tags, 'Module');
	}

	public function getView($name, array $tags = array()){
		return $this->getTemplate($name, $tags, 'View');
	}

	private function includeCSS()
	{
	   $result = '';
       if($this->registry->admincp){
            $cssFile = $this->configuration['css_files'];
            foreach($cssFile as $value)
                $result .= '<link rel="stylesheet" href="' . BSTO_ROOT_PATH . 'views/' . $this->configuration['css_dir'] . $value. '" type="text/css" media="screen" />
                ';
       }
       else{
    	   if(!$this->registry->db->get('configManager')->minify)
    	       $cssFile = $this->configuration['css_files'];
               
           else
                $cssFile = $this->configuration['css_minify'];
                
           foreach($cssFile as $value)
                $result .= '<link rel="stylesheet" href="' . BSTO_ROOT_PATH . 'views/' . $this->configuration['css_dir'] . $value. '" type="text/css" media="screen" />
            ';
       } 
       return $result;
	}


	private function includeExtraCSS()
	{
		$result = '';
		$cssFile = $this->configuration['extra_css_files'];
		$cond = $cssFile[0];
		for($i = 1; $i < count($cssFile); $i++){
			$result .= '
<!--[if $cond>
<link rel="stylesheet" href="' . BSTO_ROOT_PATH . 'views/' . $this->configuration['css_dir'] . $cssFile[$i]. '" type="text/css" media="screen" />
<![endif]-->
';
		}
		return $result;
	}

	private function includeJS()
	{

		$result = '';
        if($this->registry->admincp){
             $jsFile = $this->configuration['js_files'];
             foreach($jsFile as $value)
    			$result .= '<script src="' . BSTO_ROOT_PATH . 'views/' . $this->configuration['js_dir'] . $value. '" type="text/javascript"></script>
                 ';
        }
        else{
            if(!$this->registry->db->get('configManager')->minify)
                $jsFile = $this->configuration['js_files'];
            else 
                $jsFile = $this->configuration['js_minify'];
                
    		foreach($jsFile as $value){
    			$result .= '<script src="' . BSTO_ROOT_PATH . 'views/' . $this->configuration['js_dir'] . $value. '" type="text/javascript"></script>
                 ';
    		}
        }
		return $result;
	}

	private function addCustomJS($flag)
	{
		if(!$flag){
			$result = '
<script type="text/javascript">
    var fileLoadingImage = "'.$this->registry->router->getRoot().'views/images/loading.gif";		
    var fileBottomNavCloseImage = "'.$this->registry->router->getRoot().'views/images/closelabel.gif";
    var varUploadBtn = "'.$this->registry->router->getRoot().'views/images/forms/upload_file.gif";
    var ImageURL = "'.$this->registry->router->getRoot().'views/images/forms/calendarIcon.jpg";
    var NextURL = "'.$this->registry->router->getRoot().'views/images/forms/calendarNext.gif";
    var PrevURL = "'.$this->registry->router->getRoot().'views/images/forms/calendarPrev.gif";
    var ajaxUrl = "'.$this->registry->router->getRoot().'";
    var bookPath = "'.$this->registry->router->getRoot().'book";
</script>
';
		}
		else {
            $result = '';
		}
		return $result;
	}

	private function getPageHeaderTag()
	{
		return $this->addCustomJS(false). $this->includeCSS()  . $this->includeJS();
	}

	public function getCatContent($cats)
	{
		$result = '';
		foreach($cats as $ele){
			$result .= '
            <li><a href="'.BSTO_ROOT_PATH.'category/'.$ele->get('cid').'">'.$ele->get('name').'</a></li>
            ';
		}
		return $result;
	}

	public function getFamousContent($famous)
	{
		$result = '';
		$count = 0;
        $limit = count($famous);
           
        foreach($famous as $ele){
			$count ++;
            if($count < $limit){
                $result .= 
'
<div class="element">
        <span class="image_text">#'.$count.'</span>
        <div class="image_top">
            <img src="'.BSTO_ROOT_PATH.'views/images/top.png" width="30px" style="margin: -2px 0px 0px 10px;" alt="" title="" class="thumb" border="0"/>
        </div>
        <div class="image">
            <a href="'.BSTO_ROOT_PATH.'detail/'.$ele['nid'].'">
            <img src="'.BSTO_ROOT_PATH.'views/images/thumbnail/'.$ele['thumbnail'].'" width="60px" height="100px" class="thumb" border="0"/> </a>
        </div>
        <div class="content">
            <a href="'.BSTO_ROOT_PATH.'detail/'.$ele['nid'].'">
            <li class="bookname">'.$ele['title'].'</a></li>
            <li class="bookname">'.$ele['username'].'</li>
            <li>Like: '.$ele['like'].'</li>
            <li>Share: '.$ele['share'].'</li>
            <li>Retweet: '.$ele['retweet'].'</li>
            <li class="point">Point: '.$ele['point'].'</li>                                              
        </div>               
    </div>
    ';    
            }else{
                $result .= 
'
<div class="elementLast">
    <span class="image_text">#'.$count.'</span>
    <div class="image_top"><img src="'.BSTO_ROOT_PATH.'views/images/top.png" width="30px" style="margin: -2px 0px 0px 10px;" class="thumb" border="0"/>'.'</div>
    <div class="image">
        <a href="'.BSTO_ROOT_PATH.'detail/'.$ele['nid'].'">
        <img src="'.BSTO_ROOT_PATH.'views/images/thumbnail/'.$ele['thumbnail'].'" width="60px" height="100px" class="thumb" border="0"/> </a>
    </div>
    <div class="content">'.'<a href="'.BSTO_ROOT_PATH.'detail/'.$ele['nid'].'">
        <li class="bookname">'.$ele['title'].'</a></li>
        <li class="bookname">'.$ele['username'].'</li>
        <li>Like: '.$ele['like'].'</li>
        <li>Share: '.$ele['share'].'</li>
        <li>Retweet: '.$ele['retweet'].'</li>
        <li class="point">Point: '.$ele['point'].'</li>                                              
    </div>              
</div>
    ';    
            }
			
			 
			if($count == $limit){
				break;
			}
	  }
		return $result;
	}
	
    public function getNewBook($newBook){
        $result = '';
		$count = 0;
        $limit = count($newBook);
        
        foreach($newBook as $ele){
			$count ++;
            if($count < $limit){
                $result .= '<div class="element">'.
                                '<span class="image_text">#'.$count.'</span>'.
                                '<div class="image_top"><img src="'.BSTO_ROOT_PATH.'views/images/top.png" width="30px" style="margin: -2px 0px 0px 10px;" alt="" title="" class="thumb" border="0"/>'.'</div>'.
                                '<div class="image"><a href="'.BSTO_ROOT_PATH.'detail/'.$ele->get('nid').'"><img src="'.BSTO_ROOT_PATH.'views/images/thumbnail/'.$ele->get('thumbnail').'" width="60px" height="100px" alt="" title="" class="thumb" border="0"/> </a></div>'.
                                '<div class="content">'.'<a href="'.BSTO_ROOT_PATH.'detail/'.$ele->get('nid').'"><li class="bookname">'.$ele->get('title').'</a></li>'.
                                        '<li class="bookname">'.$ele->get('username').'</li>'.
                                        '<li>Like: 0</li>'.
                                        '<li>Share: 0</li>'.
                                        '<li>Retweet: 0</li>'.
                                        '<li class="point">Point: 0</li>'.                                                                                 
                                '</div>'.               
                            '</div>';
			}else{
			     $result .= '<div class="elementLast">'.
                                '<span class="image_text">#'.$count.'</span>'.
                                '<div class="image_top"><img src="'.BSTO_ROOT_PATH.'views/images/top.png" width="30px" style="margin: -2px 0px 0px 10px;" alt="" title="" class="thumb" border="0"/>'.'</div>'.
                                '<div class="image"><a href="'.BSTO_ROOT_PATH.'detail/'.$ele->get('nid').'"><img src="'.BSTO_ROOT_PATH.'views/images/thumbnail/'.$ele->get('thumbnail').'" width="60px" height="100px" alt="" title="" class="thumb" border="0"/> </a></div>'.
                                '<div class="content">'.'<a href="'.BSTO_ROOT_PATH.'detail/'.$ele->get('nid').'"><li class="bookname">'.$ele->get('title').'</a></li>'.
                                        '<li class="bookname">'.$ele->get('username').'</li>'.
                                        '<li>Like: 0</li>'.
                                        '<li>Share: 0</li>'.
                                        '<li>Retweet: 0</li>'.
                                        '<li class="point">Point: 0</li>'.                                                                                 
                                '</div>'.               
                            '</div>';
			} 
			if($count == $limit){
				break;
			}
	  }
		return $result;
    }
    
	
	public function setMenuKey($key)
	{
		if(!$this->registry->admincp){
			$this->menuKey = $key;
		}
		else $this->menuKeyACP = $key;
	}



	public function getMenuTemplateReplace($tags)
	{
		if(!$this->registry->admincp){
			$tags['home']           = '';
			$tags['about']          = '';
			$tags['category']       = '';
			$tags['special']        = '';
			$tags['myaccout']       = '';
			$tags['register']       = '';
			$tags['contact']        = '';
			
			$tags[$this->menuKey]   = 'class="selected"';
			
		}
		else {
			$tags['user']               = 'select';
			$tags['category']           = 'select';
			$tags['book']               = 'select';
			$tags['static']             = 'select';
			$tags['setting']            = 'select';
			$tags['dashboard']          = 'select';
			$tags['cron']				= 'select';
            $tags['dbbackup']			= 'select';
            $tags['deal']				= 'select';
            
			$tags['userShow']           = '';
			$tags['categoryShow']       = '';
			$tags['bookShow']           = '';
			$tags['staticShow']         = '';
			$tags['settingShow']        = '';
			$tags['dashboardShow']      = '';
			$tags['cronShow']      		= '';
			$tags['dbbackupShow']		= '';
			$tags['dealShow']			= '';
            
			$tags[$this->menuKeyACP]        = 'current';
			$tags[$this->menuKeyACP.'Show'] = ' show';
		}
		return $tags;
	}
	public function setACPMenuKey($key)
	{
		$this->menuKey = $key;
	}

	public function getTableSelectOption()
	{
		$fullOption = <<<EOT
					<option value="user">Users</option>
					<option value="category">Categories</option>
					<option value="static">Static</option>
					<option value="config">Settings</option>
					<option value="dashboard">Dashboard</option>			
EOT;
		return $fullOption;
	}

	public function getPageContent($name, $title, $content, array $tags = array())
	{
		// current User
		$user = $this->registry->db->get('userManager')->getCurrentUser();
    
		if(!$this->registry->admincp){// FRONT-END

			$aboutOurStore = array_pop($this->registry->db->get('staticManager')->getAboutOurStore());
			if ($aboutOurStore->get('value') == 'Default Page') {
				$pic = ' ';
			} else {
				$pic = '<img src="{bstoViewPath}images/about.gif" alt="" title="" class="right" id="aboutourstorepic"/>';
			}
				
			$cat = $this->getCatContent($this->registry->db->get('catManager')->getCategory());
			$famousBook = $this->registry->db->get('bookManager')->getFamousBook();
            $famousContent = $this->getFamousContent($famousBook);
            $newBook = $this->registry->db->get('bookManager')->getNewLimitByUser(0, 20);
            $newContent = $this->getNewBook($newBook);
          	$mostFamous = '';
           
            $con = $famousBook?$famousContent:$newContent;
            $mostFamous = 
'<div id="famous">
    <div class="title" >
        <span class="title_icon"><img src="'.BSTO_ROOT_PATH.'views/images/bullet5.gif" alt="" title=""></span>
        Famous Books
    </div>
    <div id="famousContent">
        <div class="scrollbar">
            <div class="track">
                <div class="imagethumb">
                    <div class="end"></div>
                </div>
            </div>
        </div>
        <div class="viewport">
            <div class="overview">
            '. $con.'    
            </div>
        </div>
    </div>
</div>';    
			$moduleTags = array('bstoHeader'    => $this->getPageHeaderTag(),
                                'bstoMenu'      => $this->getModule('menu', $tags),
                                'bstoAbout'     => $this->getModule('about', array('bstoModuleTitle' => $aboutOurStore->get('value'))),
                                'bstoCat'       => $this->getModule('cat', $tags),
                                'bstoFooter'    => $this->getModule('footer', $tags),
            					'bstoAboutContent' => $aboutOurStore->get('detail'),
								'bstoAboutPicture' => $pic,
								'bstoMostFamous'=> $mostFamous,
            					'bstoCatContent' => $cat,
								'bstoContent'	=> $content,
								'loginButton'	=> '',
								'login'         => $tags['login'],
			);
            
            if (isset($tags['bstoHead'])){
				$moduleTags['bstoHead'] = $tags['bstoHead'];
               
               
            }
			if (isset($tags['bookName'])){
				$moduleTags['bookName'] = $tags['bookName'];
			}
			if (isset($tags['id'])){
				$moduleTags['id'] = $tags['id'];
			}
			if (isset($tags['bookThumbnail'])){
				$moduleTags['bookThumbnail'] = rawurlencode($tags['bookThumbnail']);
			}
			if (isset($tags['bookContent'])){
				$moduleTags['bookContent'] = $tags['bookContent'];
			}
			if (!$user){
				$moduleTags['loginButton'] = '<a class="fb_button fb_button_medium">
            									<span class="fb_button_text">Login with facebook</span>
            						   		   </a>';
			}

		}
		else {// BACK-END
			if(!isset($tags['bstoTableSelectOption'])){
				if($user->get('type') == 'Admin'){
					$tags['bstoTableSelectOption']  = $this->getTableSelectOption();
				}
				else {
					$tags['bstoTableSelectOption'] = '';
				}
			}
				
			if($user->get('type') == 'Admin'){
				$menu = 'fullmenu';
				$tags['searchForm'] = $this->getModule('searchForm', $tags);
				
			}
			else {
				$menu = 'basemenu';
				$tags['searchForm'] = '';
			}
				
			$tags['bstoFullAdminMenu'] = $this->getModule($menu, $tags);
			$tags['username'] = $user->get('username');
				
			$moduleTags = array('bstoHeader'    => $this->getPageHeaderTag(),
                                'bstoMenu'      => $this->getModule('menu', $tags),
                                'bstoFooter'    => $this->getModule('footer', $tags),
                                'bstoContent'	=> $content,
            					'bstoContentTitle' => $tags['bstoContentTitle']            										
			);
		}


		// get appropriate template
		$result = $this->getView($name, $moduleTags);

		// return output
		return str_replace('{bstoTitle}', $title, $result);
	}

	public function getStaticTableContent($page, $numOfRow) {

		$path = BSTO_ROOT_PATH."static";

		$totalStatic = $this->registry->db->get('staticManager')->countStatic();
		$numPage = ceil($totalStatic/$numOfRow);
		if ($numPage < $page) {
			$page = $numPage;
		}

		$fst = $numOfRow * ($page - 1);
		$pageLeft = $page - 1;
		if ($pageLeft <= 0){
			$pageLeft = 1;
		}
		$pageLeft = $path. "/view/". $pageLeft. "?curRow=" . $numOfRow;
		$pageFarLeft = 1;
		$pageFarLeft = $path. "/view/". $pageFarLeft. "?curRow=" . $numOfRow;
		$pageRight = $page + 1;
		if ($pageRight > $numPage){
			$pageRight = $numPage;
		}
		$pageRight = $path. "/view/". $pageRight. "?curRow=" . $numOfRow;
		$pageFarRight = $numPage;
		$pageFarRight = $path. "/view/". $pageFarRight. "?curRow=" . $numOfRow;
			

		$arrResult = $this->registry->db->get('staticManager')->getLimit($fst, $numOfRow);

		$strContentTotal = '';
		$id = 0;
		if (count($arrResult) != 0) {
			foreach ($arrResult as $ele){
				if( $id % 2 == 0 ) {
					$tags['class'] = '';
				} else {
					$tags['class'] = 'alternate-row';
				}

				/*if ($ele->get('title') == 'Default Page') {
					$tags['deleteTag'] = '';
				} else {
					$tags['deleteTag'] = '<a href="{path}/delete/{BstoPage}/{BstoId}" title="Delete" value="{BstoName}" class="icon-2 info-tooltip"></a>';
				}*/
				$tags['BstoId'] = $ele->get('nid');
				$tags['BstoName'] = $ele->get('title');
				$tags['BstoCreated'] = $ele->get('created');
				$tags['BstoPage'] = $page;
				$sub = $this->registry->template->getModule('vOneStatic', $tags);
				$strContentTotal = $strContentTotal . $sub;
				$id ++;
			}
		}
		//echo $strContentTotal;
		$strContentTotal = str_replace('{path}', $path, $strContentTotal);

		$tags['BstoContent'] = $strContentTotal;
		$tags['page'] = $page;
		$tags['pageLeft'] = $pageLeft;
		$tags['pageFarLeft'] = $pageFarLeft;
		$tags['pageRight'] = $pageRight;
		$tags['pageFarRight'] = $pageFarRight;
		$tags['pageFarRight'] = $pageFarRight;
		$tags['numPage'] = $numPage;
		$result = $this->registry->template->getModule('vstatic', $tags);
		return $result;
	}

	public function getBookTags($book, $attTag = '') {
		//$catMan = new CatManager(new DB());
		$catMan = $this->registry->db->get('catManager');
        $maxdate = $this->registry->db->get('bookManager')->getMaxDate();
		if ($attTag == '') {
			if ($book->get('special') == 1) {
				$attTag = '<span class="special_icon"><img src="'.BSTO_ROOT_PATH.'views/images/special_icon.gif" alt="" title="" /></span>';
			} else if (strtotime($book->get('created')) > strtotime($maxdate) -7*24*60*60)
			$attTag = '<span class="special_icon"><img src="'.BSTO_ROOT_PATH.'views/images/new_icon.gif" alt="" title="" /></span>';
		}
		
        $plugin = $this->registry->db->get('bookManager')->getPlugin($book->get('nid'));
        $thumbFile = dirname($_SERVER['SCRIPT_FILENAME']) .'/views/images/thumbnail/'. $book->get("thumbnail");
		
        if(!file_exists($thumbFile)){            
            $thumb = 'images.jpg';
        }
        else {
            $thumb = $book->get("thumbnail");
        }
        
		return array('bookName'    	=> $book->get("title"),
                                'bookSummary' 	=> $book->get("summary"),
								'author' 	=> $book->get("author"),
								'translator' 	=> $book->get("translator"),
								'price' 	=> $book->get("price"),                                 
				 				 'bookDetail'	=> $book->get("detail"),
								'pages'         => $book->get("pages"),
				 				 'bookThumbnail'=> $thumb,
				 				 //'bookLarge'	=> $book->get("large"),
				 				 'id'			=> $book->getURLRewrite(),//@edited by hungvjnh
				 				 'cid'			=> $book->get("cid"),
  				 			 	 'categoryName' => $catMan->getById($book->get("cid"))->get("name"),
								 'bookAttribute' => $attTag,
								 'pluginFeature' => $this->getPluginContent($plugin),								 
								 );
	}
	public function getPluginContent($pluginResult){
		$like = ($pluginResult['like'] != 0 ? $pluginResult['like'] : 0);
		$share = ($pluginResult['share'] != 0 ? $pluginResult['share'] : 0);
		$retweet = ($pluginResult['retweet'] != 0 ? $pluginResult['retweet'] : 0);
		
		$result = '
                            <div class="eachPlugin" id="like"></div>	
                            <div class="number">' . $like . '</div>
                            <div class="eachPlugin" id="share"></div>
                            <div class="number">' . $share . '</div>
                    		<div class="eachPlugin" id="retweet"></div>
                            <div class="number">' . $retweet . '</div>
                    ';
		return $result;
	}
	public function getFeatureBooksContent($books) {
		$result = '<div class="title">
                 	<span class="title_icon"><img src="'.BSTO_ROOT_PATH.'views/images/bullet1.gif" alt="" title="" /></span>Special books                 	
            	   </div>';
			
		foreach ($books as $book) {
			$sub = $this->getModule('book', $this->getBookTags($book, ' '));
			$result .= $sub;
		}
		return $result;
	}

	public function getNewBooksContent($books) {
		$result =  '<div class="title"><span class="title_icon"><img src="'.BSTO_ROOT_PATH.'views/images/bullet2.gif" alt="" title="" /></span>New books</div> ';
		$result .= '<div class="new_products">';

		$newTag = '<span class="special_icon"><img src="'.BSTO_ROOT_PATH.'views/images/new_icon.gif" alt="" title="" /></span>';
		if (count($books) == 0) {
			$result .= '<span style="color:red;"><b>There is no new book!</b></span>';
		} else {
			$result .= $this->getSmallBooks($books, $newTag);
		}
		$result .= '<div class="clear"></div></div>';
		return $result;
	}

	public function getSpecialBooksContent(array $books = array(),$pageBar)
	{
		$result = "";
		//$tmp = $this->getModule('book', array());
		foreach ($books as $book) {
			$sub = $this->getModule('book', $this->getBookTags($book));
			$result .= $sub;
		}
		return $result.$pageBar;
	}

	public function getBookDetailContent($book, $relatedBooks)
	{
		$result = $this->getModule('detail', $this->getBookTags($book));

		//get all related books
		$rb = $this->getSmallBooks($relatedBooks);
        if ($rb == ''){
            $rb = '<p>There is no related book</p>';
        }

		return str_replace('{relatedBooks}', $rb, $result);
	}

	public function getCategoryBooksContent($books, $pageBar) {
		return $this->getSmallBooks($books) . $pageBar;
	}

	public function getSmallBooks($books, $attTag = '') {
		$result = "";
		foreach ($books as $book) {
			$sub = $this->getModule('smallbook', $this->getBookTags($book, $attTag));
			$result .= $sub;
		}
		return $result;
	}

}

?>
